const Router = require("koa-router");
const { operatorPoint } = require("@services/operatorPoint");
const { Sequelize } = require("sequelize");
const { Auth } = require("@middlewares/auth");
const { UserPoint, PointRecord } = require("@models/point");
const { Admin } = require("@models/admin");
const { User } = require("@models/user");
const schedule = require("node-schedule");
const { Op } = require("sequelize");
const router = new Router({
  prefix: "/admin/record",
});

// 删除去年的积分
delPoint = async () => {
  // 查询所有过期积分
  let userPoint = await UserPoint.findAll({
    where: {
      created_at: {
        [Sequelize.Op.lt]: new Date().setFullYear(new Date().getFullYear() - 1),
      },
    },
  });
  // 删除并创建积分记录
  for (let i = 0; i < userPoint.length; i++) {
    await userPoint[i].destroy();
    await PointRecord.create({
      remove_point: userPoint[i].point,
      current_point: current_point,
      operation: `您的${userPoint[i].point}积分已过期，当前积分为${current_point}`,
      remark: "积分过期",
      operator_id: 1,
      uid: userPoint[i].uid,
    });
  }
};
const job = schedule.scheduleJob("0 0 1 * * *", delPoint);
process.on("SIGINT", function () {
  // 取消定时任务
  job.cancel();
  // 退出进程
  process.exit();
});
process.on("SIGTERM", function () {
  // 取消定时任务
  job.cancel();
  // 退出进程
  process.exit();
});

//获取积分列表
router.post("/point_list", new Auth(16).m, async (ctx, next) => {
  const { uid, page, pageSize } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  if (!uid) {
    throw new global.errs.AuthFailed("用户id不能为空");
  }

  // 查询条件

  const { count: total, rows } = await UserPoint.findAndCountAll({
    where: {
      uid: uid,
    },
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["user_point_id", "ASC"]], // 排序
    include: [
      {
        model: Admin,
        attributes: ["admin_id", "admin_name", "avatar"],
        required: false,
      },
    ],
  });

  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 积分操作记录
router.post("/record_list", new Auth(16).m, async (ctx, next) => {
  const {
    uid,
    page = 1,
    pageSize = 10,
    start_time = 0,
    end_time = new Date(),
  } = ctx.request.body;
  const offset = (page - 1) * pageSize;

  if (!uid) {
    throw new global.errs.AuthFailed("用户id不能为空");
  }
  // start_time == "" ? (start_time = 0) : start_time;
  // end_time == "" ? (end_time = new Date()) : end_time;
  // 查询条件
  const where = {
    uid,
    created_at: {
      [Op.gte]: start_time,
      [Op.lte]: end_time,
    },
  };
  const { count: total, rows } = await PointRecord.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "desc"]], // 排序
    include: [
      {
        model: Admin,
        where: { admin_id: Sequelize.col("PointRecord.operator_id") },
        attributes: ["admin_id", "admin_name", "avatar"],
        required: false,
      },
    ],
  });

  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

//添加积分
router.post("/add", new Auth(16).m, async (ctx, next) => {
  const { uid, product } = ctx.request.body;

  const user = await User.findOne({
    where: { uid },
  });

  await operatorPoint.add_point(user, product, ctx.auth.uid);

  ctx.body = {
    code: 200,
    msg: "添加成功",
  };
});

// 删除积分
router.post("/del", new Auth(16).m, async (ctx, next) => {
  const { uid } = ctx.request.body;
  if (!uid) {
    throw new global.errs.AuthFailed("参数必填");
  }

  await operatorPoint.del_point(uid, ctx.auth.uid);

  ctx.body = {
    code: 200,
    msg: "删除成功",
  };
});

// 消费积分
router.post("/consume", new Auth(16).m, async (ctx, next) => {
  const { uid, remark, point } = ctx.request.body;
  if (!(uid && remark && point)) {
    throw new global.errs.AuthFailed("全部都是必填参数");
  }

  await operatorPoint.consume_point(uid, remark, point, ctx.auth.uid);

  ctx.body = {
    code: 200,
    msg: "消费成功",
  };
});

module.exports = router;
